import React from 'react';
import {connect} from "react-redux";
import { Button, Input, Badge, message, Row, Col, Card, Icon, Popover } from 'antd';
import menuRoute from "routes/menuRoute";
import {messages} from "share/common";
import taxCodeServer from 'containers/finance-setting/tax-code/tax-code-server';
import errorMessage from "share/errorMessage";
import ListSelector from 'components/list-selector';
import chooserData from 'share/chooserData'
import ResizeTable from 'components/resize-table'
const Search = Input.Search;

class InvoiceType extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0
      },
      columns: [
        {
          title: messages('common.sequence')/*序号*/,
          dataIndex: "index",
          width: "10%",
          render: (value, record, index) => this.state.pageSize * this.state.page + index + 1
        },
        {
          title: messages('finance-setting.key132'/*费用类别*/),
          dataIndex: "expTypeName",
          width: "40%",
          render: value => <Popover content={value}> {value}</Popover>
        },
        {
          title: messages('finance-setting.key141'/*规则状态*/), dataIndex: "enable", width: "10%", render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
                   text={enabled ? messages("common.status.enable") : messages("common.status.disable")}/>)
        },
        {
          title: messages('common.operation')/*操作*/,
          dataIndex: "operate",
          width: "30%",
          render: (value, record) => this.renderOperateColumn(record)
        }],
      showInvoiceTypeModal: false,//显示新增费用类别Modal
      ruleInfo: this.props.location.state ? this.props.location.state.ruleInfo : {},//单个规则信息
      dataList: [],//规则list信息
      selectedRowKeys: [],//选中的行，用于启用或者禁用
      invoiceTypeSelectItem: chooserData['selectInvoiceType'],
      currentSelectedInvoiceTypeData: [],
      searchParam:'',
      addLoading: false
    }
  }

  componentDidMount() {
    if (!this.state.ruleInfo.id) {
      let ruleId = this.props.params.ruleId !== ':ruleId' && this.props.params.ruleId;
      this.queryRuleInfo(ruleId);
    }
    this.getList();
  }

  //渲染操作列
  renderOperateColumn = (record) => {
    let toRecordDetail = (key) => {
      let url = menuRoute.getRouteItem(key).url;
      this.context.router.push({
        pathname: url.replace(':ruleId', record.ruleId).replace(':audRuleExpTypeId', record.id),
        state: { invoiceTypeInfo: record }
      })
    };
    return (
      <div>
        <a onClick={() => toRecordDetail('invoice-type-rule')}> {messages('finance-setting.key205')/*设置发票类型规则*/}
        </a>
        <a><span className="ant-divider"/></a>
        <a onClick={() => toRecordDetail('tax-code-classify')}>
          {messages('finance-setting.key142'/*设置税务编码规则*/)}
        </a>
      </div>
    )
  };

  //查询单个规则信息
  queryRuleInfo(ruleId) {
    taxCodeServer.queryTaxCodeRuleInfo(ruleId).then(res => {
      this.setState({
        ruleInfo: res.data
      })
    }).catch(e => {
      errorMessage(e.response)
    })
  }
  //规则状态启用、禁用
  clickRuleEnable = (enable) => {
    let {selectedRowKeys, dataList} = this.state;
    this.setState({loading:true})
    taxCodeServer.enableTaxCodeExpenseType(selectedRowKeys, enable).then(res => {
      this.setState({loading:false})
      dataList.map(item => {
        if (~selectedRowKeys.indexOf(item.id)) {
          item.enable = enable;
        }
      })
      this.setState({selectedRowKeys: [], dataList});
      message.success(messages('common.operate.success')/*操作成功*/);
    }).catch(e => {
      this.setState({loading:false})
      errorMessage(e.response);
    })
  }
  //模糊查询
  searchList = (searchParam) => {
    let {pagination}=this.state;
    pagination.page=0;
    pagination.current=0;
    this.setState({
      page: 0,
      pagination,
      searchParam
    },()=>{
      this.getList();
    })
  }
  //获取规则列表
  getList = () => {
    let {page, pageSize,searchParam} = this.state;
    let ruleId = this.props.params.ruleId !== ':ruleId' && this.props.params.ruleId;
    this.setState({loading: true});
    taxCodeServer.queryTaxCodeRuleRelateExpenseType(ruleId, page, pageSize, searchParam).then(res => {
      let {pagination} = this.state;
      pagination.total = res.data.total;
      this.setState({
        dataList: res.data.rows,
        loading: false,
        pagination
      })
    }).catch(e => {
      errorMessage(e.response);
      this.setState({
        dataList: [],
        loading: false
      })
    });
  };
  //表单分页、排序处理
  handleTableChange = (pagination) => {
    let page = pagination.current;
    this.setState({
      page: page - 1,
      pagination
    }, () => {
      this.getList();
    })
  }
  //分配费用类型取消
  handleAddInvoiceTypeCancel = () => {
    this.setState({showInvoiceTypeModal: false})
  }
  //增加费用类型确认
  handleAddInvoiceTypeOK = (result) => {
    let { ruleInfo,dataList} = this.state;
    let ids = [];
    result.result.length > 0 && result.result.map(item => {
      ids.push(item.id);
    })
    if (ids.length > 0) {
      this.setState({loading: true, addLoading: true})
      taxCodeServer.relateTaxCodeToExpenseType(ruleInfo.id, ids, true).then(res => {
        message.success(messages('common.operate.success')/*操作成功*/);
        this.setState({showInvoiceTypeModal: false, addLoading: false})
        this.getList();
      }).catch(e => {
        this.setState({showInvoiceTypeModal: false, loading: false, addLoading: false})
        errorMessage(e.response)
      })
    } else {
      this.setState({showInvoiceTypeModal: false})
    }
  }
  //取消费用类型MODAL
  handleInvoiceTypeCancel = () => {
    this.setState({showInvoiceTypeModal: false})
  }
  //点击增加费用类型
  clickAddInvoiceType = () => {
    this.setState({showInvoiceTypeModal: true})
  }
  //选中的行存储
  onSelectChange = (selectedRowKeys) => {
    this.setState({selectedRowKeys})
  }
  //点击返回
  clickBack = () => {
    let {ruleInfo}=this.state;
    this.context.router.push({
      pathname: menuRoute.getRouteItem('tax-code').url,
      state: {setOfBooksId:ruleInfo.setOfBooksId || ruleInfo.setOfBookId }
    })
  }
  render() {
    const {columns, pagination, loading, dataList, showInvoiceTypeModal, ruleInfo, invoiceTypeSelectItem,
      currentSelectedInvoiceTypeData, selectedRowKeys, addLoading} = this.state;
    const {tenantMode}=this.props;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <div>
        <div style={{marginBottom: 50}}>
          <Row gutter={16}>
            <Col span={24}>
              <Card title={messages('common.baseInfo')/*基本信息*/}>
                <Col span={8} style={{paddingRight:5}}>
                  <span>{messages('finance-setting.key72'/*规则名称*/)}</span>
                  <br/>
                  {ruleInfo.ruleName}
                </Col>
                <Col span={8} style={{paddingRight:5}}>
                  <span>{messages('finance-setting.key133'/*账套名称*/)}</span>
                  <br/>
                  {ruleInfo.setOfBooksName || ruleInfo.setOfBookName}
                </Col>
                <Col span={8} style={{paddingRight:5}}>
                  <span>{messages('finance-setting.key141'/*规则状态*/)}</span>
                  <br/>
                  <Badge status={ruleInfo.enabled ? 'success' : 'error'}
                         text={ruleInfo.enabled  ? messages("common.status.enable") : messages("common.status.disable")}/>
                </Col>
              </Card>
            </Col>
          </Row>
        </div>
        <div style={{marginBottom: 20}}>
          {tenantMode && <div>
            <Button type="primary" style={{marginRight: 60}} onClick={this.clickAddInvoiceType}>{messages('finance-setting.key143'/*新增费用类别*/)}</Button>
            <Button size="small" loading={loading} disabled={selectedRowKeys.length > 0 ? false : true}
                    onClick={() => this.clickRuleEnable(true)}>{messages('common.status.enable')/*启用*/}</Button> &nbsp;&nbsp;
            <Button size="small" loading={loading}  disabled={selectedRowKeys.length > 0 ? false : true}
                    onClick={() => this.clickRuleEnable(false)}>{messages('common.status.disable')/*禁用*/}</Button>
          </div>}
          <Search
            placeholder={messages('finance-setting.key144'/*请输入费用类别*/)}
            onSearch={(value) => this.searchList(value)}
            enterButton={true}
            style={{width: 200, float: "right"}}
          />
        </div>
        <div className="table-header">
          <div className="table-header-title">{messages('common.total', {total: pagination.total})}</div>
          {/* 共total条数据 */}
        </div>
        <ResizeTable
          rowKey="id"
          rowSelection={tenantMode ? rowSelection : undefined}
          columns={columns}
          dataSource={dataList}
          onChange={this.handleTableChange}
          pagination={pagination}
          loading={loading}
          size="middle"
          bordered
        />
        <a style={{fontSize: '14px', paddingBottom: '20px'}} onClick={this.clickBack}>
          <Icon type="rollback" style={{marginRight: '5px'}}/>{messages('common.back')}
        </a>
        <ListSelector
          visible={showInvoiceTypeModal}
          confirmLoading={addLoading}
          selectedData={currentSelectedInvoiceTypeData}
          onOk={this.handleAddInvoiceTypeOK}
          onCancel={this.handleAddInvoiceTypeCancel}
          extraParams={{
            setOfBooksId: ruleInfo.setOfBooksId || ruleInfo.setOfBookId,
            pasteInvoiceNeeded: true,
            enabled: true
          }}
          selectorItem={invoiceTypeSelectItem}/>
      </div>
    )

  }

}

InvoiceType.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode,
  }
}

export default connect(mapStateToProps)(InvoiceType);
